from openerp import netsvc
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
import time
from datetime import datetime
import logging
import csv
import xml.etree.ElementTree as ET
import glob
import os

_log = logging.getLogger('smcus_bb_account')


class fleet_monitor(osv.osv):
    _name = "fleet.monitor"
    _description = "Fleet Monitor"
    _columns = {
        #Adding By Me
        'gps_date': fields.datetime('GPS Date'),
        'geo_latitude': fields.float('Geo Latitude', digits=(16,6)),
        'geo_longitude': fields.float('Geo Longitude', digits=(16,6)),
        'temperature': fields.float('Temperature', digits=(16,6)),
        'start_condition': fields.float('Start Condition', digits=(16,6)),
        'speed': fields.float('Speed', digits=(16,6)),
        'direction': fields.float('Direction', digits=(16,6)),
        'mileage': fields.float('Mileage', digits=(16,6)),
        'term_state': fields.char('Terminal Status', size=64),
        'vehicle_type': fields.char('Vehicle Type', size=64),
        'unit_id': fields.integer('Unit Id'),
        'map_show_type': fields.selection([('address', 'Address'),
                           ('coordinate', 'Coordinate')], 'Map Showing By',
                           required=True, help="""Select show by Address or Coordinate for map showing."""),
        #End Add
        'no_fleet': fields.many2one('fleet.vehicle', 'Fleet Vihicle'),
        'no_polis': fields.char('No Polis', size=64),
        'no_so': fields.many2one('sale.order', 'No.SO'),
        'koordinat': fields.float('Koordinat'),
        'address_id': fields.char('Lokasi', size=256),
        'temperatur_bot': fields.float('Temperatur bawah'),
        'temperatur_up': fields.float('Temperatur atas'),
        'temperatur_state': fields.char('Status Temperatur', size=64),
        'keterangan': fields.text('Keterangan'),
        'picking_id': fields.many2one('stock.picking', 'Picking'),

    }

    _defaults = {
        'map_show_type': 'coordinate',
    }

    def open_map(self, cr, uid, ids, context=None):
        address_obj= self.pool.get('fleet.monitor')
        partner = address_obj.browse(cr, uid, ids, context=context)[0]
        url="http://maps.google.com/maps?oi=map&q="
        if partner.map_show_type == 'address':
            url += partner.address_id and partner.address_id.replace(' ','+') or ''
        else:
            lat = partner.geo_latitude or False
            long = partner.geo_longitude or False
            coordinate = ''
            if lat and long:
                coordinate = '%s, %s'%(lat,long)
            url += coordinate
        return {
        'type': 'ir.actions.act_url',
        'url':url,
        'target': 'new'
        }
    
    def send_email(self, cr, uid, ids=False, context=None):
        fleet_obj = self.pool.get('fleet.monitor')
        email_template_obj = self.pool.get('email.template')
        template_ids = email_template_obj.search(cr, uid, [('model_id.model', '=', 'fleet.monitor')])        
        fleet_ids = fleet_obj.search(cr, uid, [('temperatur_state','!=','Done')])
        if template_ids:
            for id in fleet_ids:
                fleet_brows = fleet_obj.browse(cr, uid, id)
                picking = fleet_obj.browse(cr, uid, id).picking_id
                if fllet_browse.temperatur_up > picking.temperatur_up or fllet_browse.temperatur_bot > picking.temperatur_bot:
                    values = email_template_obj.generate_email(cr, uid, template_ids[0], id, context=context)
                    mail_mail_obj = self.pool.get('mail.mail')
                    msg_id = mail_mail_obj.create(cr, uid, values, context=context)
                    if msg_id:
                        mail_mail_obj.send(cr, uid, [msg_id], context=context)
        return True
    
    def upload_fleet(self, cr, uid, ids=False, context=None):
        fleet_obj = self.pool.get('fleet.monitor')
        id=0
        f = open("/home/hendri/Desktop/fleet_monitor.csv",'rU')
        c = csv.reader(f, skipinitialspace=True)
        for line in c:            
            a = fleet_obj.search(cr, uid, [('no_polis','=',line[0])])
            if a:
                fleet_obj.write(cr, uid, a, {'koordinat': line[1],
                                             'address_id': line[2],
                                             'temperatur_bot': line[4],
                                             'temperatur_up': line[5],
                                             'temperatur_state': line[3],})

        return True

    def cronjob_xml_link(self, cr, uid, ids, context=None):

        user_obj = self.pool.get('res.users')

        company = user_obj.browse(cr, uid, uid, context=None).company_id
        file_path = company.xml_url or ''
        try:
            if not os.path.isdir(file_path):
                raise osv.except_osv(_('Error!'),_("The Directory your input is not a directory."))

        except IOError as e:
            raise osv.except_osv(_('Error!'),_("I/O error({0}): {1}".format(e.errno, e.strerror)))
        if file_path.endswith('/'):
            file_path += '*.txt'
        else:
            file_path += '/*.txt'
        filez =  glob.glob(file_path)
        exception_id = False
        for filez1 in filez:
            tree = ET.parse(filez1)
            root = tree.getroot()
            
            for child in root:
                if child.tag == 'data':

                    carnum = child.find('CarNum').text
                    fleet_vehicles = self.pool.get('fleet.vehicle').search(cr, uid, [('license_plate', '=', carnum)], context=context)
                    if len(fleet_vehicles) > 1:
                        if not exception_id:
                            exception_id =  self.pool.get('fleet.monitor.exception').create(cr, uid, {
                                                'name': datetime.now(),
                                                })
                        self.pool.get('fleet.monitor.exception.lines').create(cr, uid, {
                                                'parent_id': exception_id,
                                                'name': "Car Number '%s' is more than one at the system."%carnum,
                                                })
                        continue
                    if not fleet_vehicles:
                        if not exception_id:
                            exception_id =  self.pool.get('fleet.monitor.exception').create(cr, uid, {
                                                'name': datetime.now(),
                                                })
                        self.pool.get('fleet.monitor.exception.lines').create(cr, uid, {
                                                'parent_id': exception_id,
                                                'name': "cannot find Car Number '%s' at the system."%carnum,
                                                })
                        continue

                    gps_date = child.find('gps_time').text
                    if self.pool.get('fleet.monitor').search(cr, uid, [('gps_date', '=', gps_date),('no_fleet', '=', fleet_vehicles[0])]):
                        continue

                    self.pool.get('fleet.monitor').create(cr, uid, {
                           'no_fleet':  fleet_vehicles[0],
                           'gps_date': child.find('gps_time').text,
                           'geo_longitude' : child.find('lon').text,
                           'geo_latitude' : child.find('lat').text,
                           'address_id' : child.find('Address').text,
                           'temperature' : child.find('Temperature').text,
                           'start_condition' : child.find('StarCond').text,
                           'speed' : child.find('Speed').text,
                           'direction' : child.find('Direction').text,
                           'mileage' : child.find('Mileage').text,
                           'term_state' : child.find('TerminalStatus').text,
                           'vehicle_type' : child.find('VehicleType').text,
                           'unit_id': child.find('unit_id').text,
                       })
        return True

    def _cronjob_xml_link(self, cr, uid, context=None):
        user_obj = self.pool.get('res.users')

        company = user_obj.browse(cr, uid, uid, context=None).company_id
        file_path = company.xml_url or ''
        try:
            if not os.path.isdir(file_path):
                raise osv.except_osv(_('Error!'),_("The Directory your input is not a directory."))

        except IOError as e:
            raise osv.except_osv(_('Error!'),_("I/O error({0}): {1}".format(e.errno, e.strerror)))
        if file_path.endswith('/'):
            file_path += '*.txt'
        else:
            file_path += '/*.txt'
        filez =  glob.glob(file_path)
        exception_id = False
        for filez1 in filez:
            tree = ET.parse(filez1)
            root = tree.getroot()
            
            for child in root:
                if child.tag == 'data':

                    carnum = child.find('CarNum').text
                    fleet_vehicles = self.pool.get('fleet.vehicle').search(cr, uid, [('license_plate', '=', carnum)], context=context)
                    if len(fleet_vehicles) > 1:
                        if not exception_id:
                            exception_id =  self.pool.get('fleet.monitor.exception').create(cr, uid, {
                                                'name': datetime.now(),
                                                })
                        self.pool.get('fleet.monitor.exception.lines').create(cr, uid, {
                                                'parent_id': exception_id,
                                                'name': "Car Number '%s' is more than one at the system."%carnum,
                                                })
                        continue
                    if not fleet_vehicles:
                        if not exception_id:
                            exception_id =  self.pool.get('fleet.monitor.exception').create(cr, uid, {
                                                'name': datetime.now(),
                                                })
                        self.pool.get('fleet.monitor.exception.lines').create(cr, uid, {
                                                'parent_id': exception_id,
                                                'name': "cannot find Car Number '%s' at the system."%carnum,
                                                })
                        continue

                    gps_date = child.find('gps_time').text
                    if self.pool.get('fleet.monitor').search(cr, uid, [('gps_date', '=', gps_date),('no_fleet', '=', fleet_vehicles[0])]):
                        continue

                    self.pool.get('fleet.monitor').create(cr, uid, {
                           'no_fleet':  fleet_vehicles[0],
                           'gps_date': child.find('gps_time').text,
                           'geo_longitude' : child.find('lon').text,
                           'geo_latitude' : child.find('lat').text,
                           'address_id' : child.find('Address').text,
                           'temperature' : child.find('Temperature').text,
                           'start_condition' : child.find('StarCond').text,
                           'speed' : child.find('Speed').text,
                           'direction' : child.find('Direction').text,
                           'mileage' : child.find('Mileage').text,
                           'term_state' : child.find('TerminalStatus').text,
                           'vehicle_type' : child.find('VehicleType').text,
                           'unit_id': child.find('unit_id').text,
                       })
        return True

fleet_monitor()

class fleet_monitor_exception(osv.osv):
    _name = "fleet.monitor.exception"
    _description = "Fleet Monitor Exception"

    _columns = {
        'name': fields.datetime('Date', required=True, select=1),
        'line_id': fields.one2many('fleet.monitor.exception.lines', 'parent_id', 'Error Lines'),
    }

fleet_monitor_exception()

class fleet_monitor_exception_lines(osv.osv):
    _name = "fleet.monitor.exception.lines"
    _description = 'Exception Lines'

    _columns = {
        'parent_id': fields.many2one('fleet.monitor.exception', "Header", required=True, select=True, ondelete="cascade"),
        'name': fields.char('Error Description', required=True, help='Error Description.'),
    }

fleet_monitor_exception_lines()


class fleet_vehicle_state(osv.Model):
    _inherit = 'fleet.vehicle.state'
    _columns = {
        'smcus_is_available': fields.boolean('Is Available State'),
        'smcus_is_leave': fields.boolean('Is Leave State'),
        'smcus_is_maintenance': fields.boolean('Is Maintenance State'),
    }

fleet_vehicle_state()

class fleet_vehicle(osv.osv):
    _inherit = 'fleet.vehicle'

    _columns = {
        'smcus_volume_capacity': fields.float('Volume (m3)'),
        'smcus_weight_capacity': fields.float('Weight (kg)'),        
        'smcus_is_available': fields.related('state_id', 'smcus_is_available', type='boolean', string='Is Available', store=True, readonly=True),
        'driver_id': fields.many2one('res.partner', 'Supir 1', help='Driver 1 of the vehicle'),
        'driver_id1': fields.many2one('res.partner', 'Supir 2', help='Driver 2 of the vehicle'),
        'no_hp1': fields.integer('No.HP'),
        'no_hp2': fields.integer('No.HP'),                
        'picking_id': fields.many2one('stock.picking', 'Picking'),
    }


    def testing(self, cr, uid, ids, context=None):
        fleet_monitor_obj= self.pool.get('fleet.monitor')
        fleet_monitor_obj.cronjob_xml_link(cr,uid,ids,context=None)
        return True


    def open_map(self, cr, uid, ids, context=None):
        
        fleet_monitor_obj= self.pool.get('fleet.monitor')
        url = "http://maps.google.com/maps/api/staticmap?zoom=14&size=640x640&maptype=roadmap"
        fleet_monitor_ids = fleet_monitor_obj.search(cr, uid, [('no_fleet','in',ids)], order='gps_date')
        if fleet_monitor_ids:
            number = 1
            for fleet_monitor in fleet_monitor_obj.browse(cr, uid, fleet_monitor_ids, context=context):
                if fleet_monitor.map_show_type == 'address':
                    url_fleet_monitor= fleet_monitor.address_id and fleet_monitor.address_id.replace(' ','+') or ''
                else:
                    lat = fleet_monitor.geo_latitude or False
                    long = fleet_monitor.geo_longitude or False
                    coordinate = ''
                    if lat and long:
                        coordinate = '%s, %s'%(lat,long)
                    url_fleet_monitor = coordinate
                url += '&markers=color:blue|label:%s|%s'%(number,url_fleet_monitor)
                number+= 1

        url+= '&sensor=false'

        return {
        'type': 'ir.actions.act_url',
        'url':url,
        'target': 'new'
        }

fleet_vehicle()

